<template>
  <div class="register-page">
    <van-nav-bar
      title="注册账号"
      left-arrow
      @click-left="onClickLeft"
    />

    <div class="logo">
      <van-image
        width="60"
        height="60"
        src="/src/assets/images/logo.png"
      />
      <div class="subtitle">新用户注册</div>
    </div>

    <div class="register-form">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="username"
            placeholder="请设置用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          >
            <template #label>
              <van-icon name="user-o" style="margin-right: 5px;" />
              用户名
            </template>
          </van-field>
          
          <van-field
            v-model="userTypeText"
            is-link
            readonly
            name="userType"
            label="用户类型"
            placeholder="请选择用户类型"
            @click="showUserTypePicker = true"
            :rules="[{ required: true, message: '请选择用户类型' }]"
          >
            <template #label>
              <van-icon name="manager-o" style="margin-right: 5px;" />
              用户类型
            </template>
          </van-field>
          <van-action-sheet 
            v-model:show="showUserTypePicker" 
            :actions="userTypeActions"
            @select="onSelectUserType"
            cancel-text="取消"
            close-on-click-action
            title="选择用户类型"
          />
          <van-field
            v-if="userType === '0'"
            v-model="villageText"
            is-link
            readonly
            name="village"
            label="所属村集体"
            placeholder="请选择所属村集体"
            @click="showvillagePicker = true" 
            :rules="[{ required: userType === '0', message: '普通农民用户请选择所属村集体' }]" 
          >
            <template #label>
              <van-icon name="manager-o" style="margin-right: 5px;" />
              所属村
            </template>
          </van-field>
          <van-action-sheet 
            v-model:show="showvillagePicker" 
            :actions="villageCollective"
            @select="onvillageSelect"
            cancel-text="取消"
            close-on-click-action
            title="请选择所属村集体"
          />
          <van-field
            v-model="phone"
            type="tel"
            name="phone"
            placeholder="请输入手机号"
            :rules="[
              { required: true, message: '请填写手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }
            ]"
          >
            <template #label>
              <van-icon name="phone-o" style="margin-right: 5px;" />
              手机号
            </template>
            <template #button>
              <van-button 
                size="small" 
                type="primary" 
                :disabled="!!timer || !phone || !/^1[3-9]\d{9}$/.test(phone)"
                @click="sendVerifyCode"
              >
                {{ codeButtonText }}
              </van-button>
            </template>
          </van-field>

          <van-field
            v-model="verifyCode"
            type="number"
            name="verifyCode"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #label>
              <van-icon name="shield-o" style="margin-right: 5px;" />
              验证码
            </template>
          </van-field>

          <van-field
            v-model="password"
            type="password"
            name="password"
            placeholder="请设置密码"
            :rules="[
              { required: true, message: '请设置密码' },
              { min: 6, message: '密码至少6位' }
            ]"
          >
            <template #label>
              <van-icon name="lock" style="margin-right: 5px;" />
              密码
            </template>
          </van-field>

          <van-field
            v-model="confirmPassword"
            type="password"
            name="confirmPassword"
            placeholder="请再次输入密码"
            :rules="[
              { required: true, message: '请确认密码' },
              { validator: validateConfirmPassword, message: '两次密码不一致' }
            ]"
          >
            <template #label>
              <van-icon name="passed" style="margin-right: 5px;" />
              确认密码
            </template>
          </van-field>
        </van-cell-group>

        <div class="agreement">
          <van-checkbox v-model="agreed" shape="square">
            我已阅读并同意
            <span class="link" @click="showAgreement">《用户协议》</span>
            和
            <span class="link" @click="showPrivacy">《隐私政策》</span>
          </van-checkbox>
        </div>

        <div style="margin: 24px 16px">
          <van-button 
            round 
            block 
            type="primary" 
            native-type="submit"
            :disabled="!agreed"
          >
            注册
          </van-button>
        </div>
      </van-form>
    </div>

    <div class="login-link">
      已有账号？
      <router-link to="/login" class="link">立即登录</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  showToast, 
  showDialog, 
  Field,
  Form,
  CellGroup,
  Button,
  NavBar,
  Checkbox,
  Icon,
  Image as VanImage,
  ActionSheet
} from 'vant'
import { useUserStore } from '@/store/modules/user'
import {getVillageCollective} from '@/api/villageCollective'
import api from '@/api'

const router = useRouter()
const userStore = useUserStore()

const username = ref('')
const phone = ref('')
const verifyCode = ref('')
const password = ref('')
const confirmPassword = ref('')
const agreed = ref(false)
const timer = ref(null)
const countdown = ref(60)
const villageCollective = reactive([])
const villageText = ref('')
const showvillagePicker = ref(false) // 修正变量名
const villageId = ref('') // 新增村集体ID存储
// 用户类型相关
const showUserTypePicker = ref(false)
const userType = ref('')
const userTypeText = ref('')
const userTypeActions = [
  { name: '普通农民', value: '0' },
  { name: '村集体', value: '1' }
]

const fetchVillageCollectives = async () => {
  try {
    const res = await getVillageCollective()
    res.forEach(item => {
      villageCollective.push(item)
    })
    console.log(villageCollective);
    
  } catch (error) {
    console.error('查询失败', error.message)
  }
}
fetchVillageCollectives()

// 用户类型选择
const onSelectUserType = (action) => {
  userType.value = action.value
  userTypeText.value = action.name
  showUserTypePicker.value = false
}

const onvillageSelect = (action) => {
  villageText.value = action.name
  villageId.value = action.id // 存储村集体ID
  showvillagePicker.value = false
}

// 验证码按钮文字
const codeButtonText = computed(() => {
  if (timer.value) {
    return `${countdown.value}秒后重发`
  }
  return '发送验证码'
})

// 验证确认密码
const validateConfirmPassword = (value) => {
  return value === password.value
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 发送验证码
const sendVerifyCode = () => {
  if (!phone.value) {
    showToast('请先输入手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    showToast('手机号格式错误')
    return
  }
  
  // 开始倒计时
  countdown.value = 60
  timer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)
  
  showToast('验证码已发送')
}

// 显示用户协议
const showAgreement = () => {
  showDialog({
    title: '用户协议',
    message: '这里是用户协议内容...',
    confirmButtonText: '我知道了'
  })
}

// 显示隐私政策
const showPrivacy = () => {
  showDialog({
    title: '隐私政策',
    message: '这里是隐私政策内容...',
    confirmButtonText: '我知道了'
  })
}

// 表单提交
const onSubmit = async (values) => {
  if (!userType.value) {
    showToast('请选择用户类型')
    return
  }
  if (userType.value === '0' && !villageText.value) {
    showToast('普通农民用户请选择所属村集体')
    return
  }

  try {
    console.log({
      username: username.value,
      password: password.value,
      phone: phone.value,
      is_admin: userType.value === '1',
      village_id: userType.value === '0' ? villageId.value : null
    });
    // 调用API注册新用户
    const res = await api.user.register({
      username: username.value,
      password: password.value,
      phone: phone.value,
      is_admin: userType.value === '1',
      village_id: userType.value === '0' ? villageId.value : null
    })
    
    
    if (res.code === 0) {
      showToast('注册成功')
      router.push('/login')
    } else {
      showToast(res.message || '注册失败')
    }
  } catch (error) {
    showToast('注册失败：' + error.message)
  }
}
</script>

<style lang="scss" scoped>
.register-page {
  min-height: 100vh;
  background-color: #fff;

  .logo {
    text-align: center;
    margin: 24px 0 40px;

    .subtitle {
      margin-top: 12px;
      font-size: 16px;
      color: #969799;
    }
  }

  .register-form {
    .agreement {
      margin: 16px;
      font-size: 14px;
      color: #969799;

      .link {
        color: #1989fa;
      }
    }
  }

  .login-link {
    margin-top: 24px;
    text-align: center;
    font-size: 14px;
    color: #969799;

    .link {
      color: #1989fa;
      margin-left: 4px;
    }
  }
}
</style>